// import { login, getInfo } from '@/api/user'
import { setToken, removeToken } from '@/utils/auth'
import store from '@/store'

const getDefaultState = () => {
    return {
        name: '',
        userId: '',
        avatar: ''
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_USERID: (state, userId) => {
        state.userId = userId
    }
}

const actions = {
    // user login
    login ({ commit }, record) {
        const { name, avatar, userId } = record
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_USERID', userId)
        setToken('useLogin', name)
        sessionStorage.setItem('isLogin', true)
        sessionStorage.setItem('userId', userId)
        store.dispatch('routes/changeRoutes')
    },

    // get user info
    getInfo ({ commit, state }) {
        // return new Promise((resolve, reject) => {
        //   getInfo(state.token).then(response => {
        //     const { data } = response

        //     if (!data) {
        //       return reject('Verification failed, please Login again.')
        //     }

        //     const { name, avatar } = data

        //     commit('SET_NAME', name)
        //     commit('SET_AVATAR', avatar)
        //     resolve(data)
        //   }).catch(error => {
        //     reject(error)
        //   })
        // })
    },

    // user logout
    logout ({ commit, dispatch, state }) {
        commit('RESET_STATE')
        commit('CHANGE_ROUTES', [])
        removeToken('useLogin')
        dispatch('tagsView/delAllViews', null, { root: true })
        sessionStorage.clear()
        location.reload()
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

